﻿using CaseManagerLibrary.Http;
using CaseManagerLibrary.Models;
using Newtonsoft.Json;
using PSDDownloadService.SystemSettings;
using PSDLib.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PSDBurnService
{
    public class BurnManager
    {
        private BurnServiceContext context;

        /// <summary>
        /// 所有刻录任务列表
        /// </summary>
        public BurnTaskList BurnTasks { get; set; }

        /// <summary>
        /// 同步刻录任务列表
        /// </summary>
        public List<BurnTask> SyncBurnList { get; set; }

        ///// <summary>
        ///// 正在刻录中的光盘列表
        ///// </summary>
        //public List<BurnRuntime> BurningDVDList { get; set; }

        /// <summary>
        /// 刻录运行时状态
        /// </summary>
       

        public BurnManager(BurnServiceContext ctx)
        {
            context = ctx;

            BurnTasks = new BurnTaskList();
            SyncBurnList = new List<BurnTask>();
            //BurningDVDList = new List<BurnRuntime>();
          
        }

        /// <summary>
        /// 添加一个刻录任务
        /// </summary>
        /// <param name="task"></param>
        public void AddTask(BurnTask task)
        {
            BurnTasks.Add(task);

            if (task.BurnMode == (int)BurnMode.ImmediateBurn)
            {
                ImmediateBurn(task);
            }
            else if (task.BurnMode == (int)BurnMode.SyncBurn)
            {
                SyncBurn(task);
            }
        }

        /// <summary>
        /// 获取一个可用刻录光驱，并开始刻录
        /// </summary>
        /// <param name="dvd"></param>
        /// <returns></returns>
        public bool BeginBurnDVD(dl_burn_dvd dvd)
        {
            bool success = false;

            var device = context.DeviceManager.GetStandbyDevice();

            if (device != null)
            {
                var task = BurnTasks.Where(t => t.BurnInfo.id == dvd.burn_id).FirstOrDefault();

                if (task != null)
                {
                    var files = task.FileList.Where(t => t.dvd_id == dvd.id).ToList();

                    foreach (var file in files)
                    {
                        device.AddFile(file.file_path);
                    }

                    var burningDVD = new BurningDVD()
                    {
                        Id = dvd.id,
                        BurnInfo = task.BurnInfo,
                        DVD = dvd,
                        Files = files
                    };

                    //BurningDVDList.Add(burning);
                    context.BurnRuntime.BurningDVD.Add(burningDVD);

                    device.StartBurn(dvd.dvd_title, false, true);
                }
            }

            return success;
        }

        /// <summary>
        /// 结束刻录，将光盘从正在刻录光盘列表中移除
        /// </summary>
        /// <param name="dvdId"></param>
        public void EndBurnDVD(dl_burn_dvd dvd)
        {
            var burningDVD = context.BurnRuntime.BurningDVD.Where(t => t.Id == dvd.id).FirstOrDefault();

            if (burningDVD != null)
            {
                context.BurnRuntime.BurningDVD.Remove(burningDVD);

                if (dvd.state == (int)BurnDVDState.刻录完成)
                {
                    var task = BurnTasks.Where(t => t.BurnInfo.id == burningDVD.BurnInfo.id).FirstOrDefault();

                    if (task != null)
                    {
                        bool finish = true;
                        foreach (var d in task.DVDList)
                        {
                            if (d.state < (int)BurnDVDState.刻录完成)
                            {
                                finish = false;
                                break;
                            }
                        }

                        if (finish)
                        {
                            task.BurnInfo.state = (int)BurnDVDState.刻录完成;

                            HttpHelper.Post<HResult>(AppSettings.Setting.API.BurnComplete, JsonConvert.SerializeObject(task.BurnInfo));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 立即刻录，要刻录的文件一次性提交
        /// </summary>
        /// <param name="task"></param>
        private void ImmediateBurn(BurnTask task)
        {
            foreach (var dvd in task.DVDList)
            {
                if (task.BurnInfo.burn_type == (int)BurnType.单光驱刻录)
                {
                    BeginBurnDVD(dvd);
                }
            }
        }

        #region 同步刻录相关
        /// <summary>
        /// 同步刻录，与文件下载同步，满一张光盘容量后刻录一张
        /// </summary>
        /// <param name="task"></param>
        private void SyncBurn(BurnTask task)
        {
            task.OnDVDReadyToBurn += Task_OnDVDReadyToBurn;
            SyncBurnList.Add(task);
        }

        /// <summary>
        /// 光盘准备刻录事件
        /// </summary>
        /// <param name="dvd"></param>
        private void Task_OnDVDReadyToBurn(dl_burn_dvd dvd)
        {
            BeginBurnDVD(dvd);
        }


        /// <summary>
        /// 添加刻录文件
        /// </summary>
        /// <param name="burnId"></param>
        /// <param name="file"></param>
        public void AddBurnFile(string burnId, dl_files file)
        {
            var task = BurnTasks.Where(t => t.BurnInfo.id == burnId).FirstOrDefault();

            if (task != null)
            {
                dl_burn_files bf = new dl_burn_files();
                bf.id = Guid.NewGuid().ToString();
                bf.burn_id = burnId;
                bf.dl_task_id = task.BurnInfo.dl_task_id;
                bf.file_id = file.id;
                bf.file_name = file.file_name;
                bf.file_path = file.file_path;
                bf.file_size = file.file_size;
                bf.dvd_file_name = file.file_name;
                bf.dvd_file_path = "";
                bf.state = 0;

                task.AddFile(bf);
            }
        }

        #endregion
    }
}
